#ifndef _WX_DIRTY_H
#define _WX_DIRTY_H

#include <vector>
#include <string>
#include <sys/shm.h>
#include <sstream>
#include <map>
#include <set>
#include <stdint.h>
#include <stdlib.h>


#define MAX_DIRTY_LEN 30
#define MAX_LINE_LEN 200

using namespace std;

typedef struct DIRTY_ENTRY
{
	unsigned char words[MAX_DIRTY_LEN];
	unsigned char src[20];
	unsigned short len;
	unsigned int next;
	unsigned int type;
	unsigned int level;
} DIRTY_ENTRY;

typedef struct SLOT_ENTRY
{
	unsigned int next;
} SLOT_ENTRY;

typedef struct 
{
	unsigned int curOffset;
	//unsigned int segOffset;
	unsigned int bottomOffset;
} DIRTY_MEM_HEAD;


typedef map<DIRTY_ENTRY*, int32_t> MATCH_RLT;
typedef vector<string> MATCH_WDS;
typedef pair<unsigned short,unsigned short> PSS;

class Dirty
{
private:
	Dirty();
	Dirty(const Dirty&);
	Dirty& operator = (const Dirty&);
public:
	bool checkDirty(string &src, const char* buf,  size_t len, stringstream &outbuf);
//	MATCH_WDS searchDirty(const char *buf);
	bool init(key_t key);
	//bool addDirty(string &src, const string& theWord, int32_t type);
	bool addDirty(string &src, const string& theWord,pair<int8_t,int8_t> dirty);
	static Dirty* getInstance()
	{
		if(pDirty == NULL)
			pDirty = new Dirty();
		
		return pDirty;
	}
	
private:
	//bool addDirty(const string& theWord);
	bool getShareMem(key_t key,size_t size);
	void* memAlloc();
	PSS getNextWord(const unsigned char* src,unsigned int start);
	void* getEntry(unsigned short index);
	void* getDirtyEntry(unsigned short index);
	bool loadDirtyFromFile(string &src);
	bool loadDirtyFromMySQL(string &src);

	
private:
	char* pShare;
	bool  pNewMem;
	DIRTY_MEM_HEAD* pMemHead;
	set<string> 	srcSet;
	static Dirty* pDirty;
	int32_t memkey;
	pthread_mutex_t mutex;
};

inline void* Dirty::getEntry(unsigned short index)
{
	//return pShare + sizeof(DIRTY_MEM_HEAD) + index * sizeof(SLOT_ENTRY);
	return pShare + index * sizeof(SLOT_ENTRY);
}

inline void* Dirty::getDirtyEntry(unsigned short index)
{
	return pShare + sizeof(DIRTY_MEM_HEAD) + 65536 * sizeof(SLOT_ENTRY) + index * sizeof(DIRTY_ENTRY);
	//return pShare + 65536 * sizeof(SLOT_ENTRY) + index * sizeof(DIRTY_ENTRY);
}




#endif
